package com.singlemountaintech.haogongjiang.http.interceptor;

import com.singlemountaintech.haogongjiang.utils.LogUtils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by LUOLI on 2018/2/12.
 */

public class LoggingInterceptor implements Interceptor {
    private static final String TAG = "LoggingInterceptor";
    @Override
    public Response intercept(Chain chain) throws IOException {
        //这个chain里面包含了request和response，所以你要什么都可以从这里拿
        Request request = chain.request();
        HttpUrl url = request.url();
        long t1 = System.nanoTime();//请求发起的时间
        boolean isDebug = false;
        if (isDebug) {
            LogUtils.info(TAG,"------------开始--------------");
            LogUtils.info(TAG,String.format("发送请求 %s",
                    request.url(), chain.connection(), request.headers()));
        }

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();//收到响应的时间

        //这里不能直接使用response.body().string()的方式输出日志
        //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
        //个新的response给应用层处理
        ResponseBody responseBody = response.peekBody(1024 * 1024);
        if (isDebug) {
            LogUtils.info(TAG,String.format("返回json:%s",responseBody.string()));
            LogUtils.info(TAG,"------------结束--------------");
        }
        return response;
    }
}
